package cn.szabadsag.base.interceptor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * 拦截器
 *
 * @author yangcong
 * @date 2022年03月12日 21:13
 * @since
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {


    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 前置拦截
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //  获取请求头的token
        String token = request.getHeader("U-TOKEN");
        System.out.println("获取请求头的token:" + token);

        if(token != null) {
            //  从redis中获取token的值
            Object o = redisTemplate.opsForValue().get(token);
            System.out.println("从redis中获取token的值:" + o);
            if(o != null) {
                //  刷新过期时间
                redisTemplate.opsForValue().set(token,o,30, TimeUnit.MINUTES);
                return true;
            }
        }
        //  设置响应类型及编码格式
        response.setContentType("application/json;charset=UTF-8");
        //  获取输出流对象
        PrintWriter writer = response.getWriter();
        //  返回一个没有登录JSON提示给前端
        //  {"success":"fasle","message":"noAuth"}
        //writer.println("\"success\":\"fasle\",\"message\":\"noAuth\"");
        writer.println("{\"success\":false,\"message\":\"noAuth\"}");

        //  关闭IO流
        writer.close();

        return false;
    }
}
